package com.zhuangjie.mvc.validator.handler;

import com.zhuangjie.mvc.validator.annotate.ValidTimeRangeString;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class ValidTimeRangeStringValidator implements ConstraintValidator<ValidTimeRangeString, String> {
    private ValidTimeRangeString validTimeRangeString;

    @Override
    public void initialize(final ValidTimeRangeString constraintAnnotation) {
        validTimeRangeString = constraintAnnotation; // 获取自定义分隔符
    }

    @Override
    public boolean isValid(final String timeRanges, final ConstraintValidatorContext context) {
        if (timeRanges == null) {
            return true;
        }
        // HH:mm${separator}HH:hh
        String[] timeRangeList = timeRanges.split(validTimeRangeString.delimiter());
        for (String timeRangeValue : timeRangeList) {
            // HH:mm${separator}HH:hh
            String[] times = timeRangeValue.split(validTimeRangeString.rangeDelimiter());
            if (times.length != 2) return false;
            // 检查小时的合法性与分钟的合法性
            for (String time : times) {
                if (!isValidTime(time)) {
                    return false;
                }
            }
            // 检查startTime是否在endTime之前
            if (times[0].compareTo(times[1]) > 0) {
                return false;
            }
        }
        return true;
    }
    /**
     * 是有效时间格式
     *
     * @param time 时间
     * @return boolean
     */
    public static boolean isValidTime(String time) {
        if (time == null || !time.contains(":")) return false;
        String[] hhMM = time.split(":");
        if (hhMM.length != 2) return false;
        Byte hh = Byte.valueOf(hhMM[0]);
        Byte mm = Byte.valueOf(hhMM[1]);
        return !(hh < 0 || hh > 23 || mm < 0 || mm > 59);
    }
}